package cn.com.tom.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse resppose = (HttpServletResponse) resp;
        String uri = request.getRequestURI();
        System.out.println("uri=" + uri);
        if (uri.equals(request.getContextPath() + "/")) {
            resppose.sendRedirect(request.getContextPath() + "/user/front");
        } else if (uri.contains("/asset") || uri.contains("/front") || uri.contains("/contact/save")) {
            chain.doFilter(req, resp);
        } else if (uri.contains("/admin") || uri.contains("/remove") || uri.contains("save")) {
            HttpSession session = request.getSession();
            Object user = session.getAttribute("user");
            if (user != null) {
                chain.doFilter(req, resp);
            } else {
                resppose.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        } else {
            chain.doFilter(req, resp);
        }
    }
}
